package dang.common;

import java.io.IOException;
import java.util.UUID;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class VerifyUtil {
	/**
	 * 生成注册验证Code
	 * @param userId
	 * @return
	 */
	public static String generateCode(int userId){
		UUID uuid = UUID.randomUUID();
		String code = uuid.toString()+"-"+userId;
		BASE64Encoder encoder = new BASE64Encoder();
		String code64 = encoder.encode(code.getBytes());
		return code64;
	}
	
	/**
	 * 获取UUID
	 * @param code64
	 * @return
	 */
	public static String getUUID(String code64){
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] bs = decoder.decodeBuffer(code64);
			String code = new String(bs);
			int index = code.lastIndexOf("-");
			return code.substring(0,index);
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 获取userID
	 * @param code64
	 * @return
	 */
	public static String getUserID(String code64){
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] dist = decoder.decodeBuffer(code64);
			String code = new String(dist);
			int index = code.lastIndexOf("-")+1;
			return code.substring(index);
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	
	public static void main(String[] args){
		String code = generateCode(1);
		System.out.println(code);
		String userId = getUserID(code);
		System.out.println(userId);
	}
	
}
